package com.x.erp.service;

import com.alibaba.fastjson.JSON;
import com.x.erp.dao.CarDao;
import com.x.erp.dao.CarImageDao;
import com.x.erp.dao.CityMappingThirdpartyDao;
import com.x.erp.dao.ModelMappingThirdpartyDao;
import com.x.erp.model.Car;
import com.x.erp.model.CarImage;
import com.x.erp.model.Market;
import com.x.erp.thirdparty.CarMappingThirdparty;
import com.x.erp.thirdparty.CityMappingThirdparty;
import com.x.erp.thirdparty.FirstCarInfo;
import com.x.erp.thirdparty.ModelMappingThirdparty;
import com.x.erp.util.Constant;
import com.x.erp.util.FirstCarApi;
import com.x.erp.util.FirstCarResult;
import com.x.framework.service.BaseService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Component
public class FirstCarService extends BaseService {

	private Logger logger = LoggerFactory.getLogger(FirstCarService.class);
	
	@Autowired
	private ModelMappingThirdpartyDao modelMappingThirdpartyDao;

	@Autowired
	private CarMappingThirdpartyService carMappingThirdpartyService;

	@Autowired
	private CityMappingThirdpartyDao cityMappingThirdpartyDao;

	@Autowired
	private MarketService marketService;

	@Autowired
	private CarImageDao carImageDao;

	@Autowired
	private FirstCarApi firstCarApi;

	@Autowired
	private CarDao carDao;

	// 发布车源
	public void insertOrUpdateCarFirst(Car car) {
		if(StringUtils.isEmpty(Constant.FIRST_URL) || Constant.FIRST_URL.contains("test")){
			return;
		}
		if(car != null && StringUtils.isNotEmpty(car.getCarId())) {
			//获取车辆信息
			car =  getCarInfo(car);
			if(car == null){
				logger.info("获取车辆信息失败！");
				return;
			}
			//判断价格是否为面议
			if (car.getCarRetailPrice() != null && car.getCarRetailPrice() == new BigDecimal(0)){
				logger.info("该车辆为面议车辆，不推送第一车网！");
				return;
			}
			//判断是否为新车（新车不推送第一车网）
			if (car.getCarLicenceState() != null && car.getCarLicenceState() == 3){
				logger.info("该车辆为新车，不推送第一车网！");
				return;
			}
			//获取登录信息
			FirstCarInfo firstCarInfo = new FirstCarInfo();
			FirstCarResult firstCarResultLogin = null;
			try {
				firstCarResultLogin = firstCarApi.login(firstCarInfo.getLoginXml());
			} catch (Exception e) {
				logger.error("第一车网登录失败！", e);
				return;
			}
			//获取车源信息
			FirstCarInfo firstCarInfoBack = getFirstCarInfo(car, firstCarResultLogin, firstCarInfo);
			if(firstCarInfoBack == null){
				logger.info("获取车辆信息失败！");
				return;
			}
			logger.info(JSON.toJSONString(firstCarInfoBack));
			//判断是否为第一次发布车源
			CarMappingThirdparty carMappingThirdparty = new CarMappingThirdparty();
			carMappingThirdparty.setCarId(car.getCarId());
			carMappingThirdparty.setCarType(1);
			List<CarMappingThirdparty> selectCarMappingThirdpartList = carMappingThirdpartyService.selectCarMappingThirdpartList(carMappingThirdparty);
			//如果不是第一次发布车源，则设为上架状态
			if(selectCarMappingThirdpartList != null && selectCarMappingThirdpartList.size() > 0){
				try {
					FirstCarResult firstCarResult = firstCarApi.createOrUpdateCar(firstCarInfoBack.getCreateOrUpdateXml(firstCarResultLogin.getSid(), firstCarResultLogin.getShop_id(), selectCarMappingThirdpartList.get(0).getCarThirdpartyId()));
					if (firstCarResult == null){
						logger.info("第一车网修改返回数据有误！");
						return;
					}
					if(StringUtils.isNotEmpty(firstCarResult.getError())){
						logger.info("第一车网修改数据失败，提示码：" + firstCarResult.getError_code() + "  ，提示信息：" + new String(firstCarResult.getError().getBytes(),"UTF-8"));
						return;
					}
					logger.info("第一车网数据修改成功！第一车网车辆ID ：" + firstCarResult.getId());
				} catch (Exception e) {
					logger.error("第一车网修改数据失败！" , e);
					return;
				}
			}else {//如果是第一次发布车源则添加车源
				// 发布车源
				Integer id = null;
				try {
					FirstCarResult firstCarResult = firstCarApi.createOrUpdateCar(firstCarInfoBack.getCreateOrUpdateXml(firstCarResultLogin.getSid(), firstCarResultLogin.getShop_id(), null));
					if (firstCarResult == null){
						logger.info("第一车网发布车源返回数据有误！");
						return;
					}
					if (StringUtils.isNotEmpty(firstCarResult.getError())) {
						logger.info("第一车网发布车源失败，提示码：" + firstCarResult.getError_code() + "  ，提示信息：" + new String(firstCarResult.getError().getBytes(),"UTF-8"));
						return;
					}
					id = firstCarResult.getId();
				} catch (Exception e) {
					logger.error("第一车网发布车辆失败！", e);
					return;
				}
				//将返回的车辆id存起来
				carMappingThirdparty.setCarThirdpartyId(id);
				carMappingThirdparty.setCarType(1);
				CarMappingThirdparty carMappingThirdpartBack = carMappingThirdpartyService.insertCarMappingThirdpart(carMappingThirdparty);
				if (carMappingThirdpartBack != null){
					logger.info("第一车网发布车辆成功！第一车网车辆ID ：" + carMappingThirdpartBack.getCarThirdpartyId());
				}
			}
		}
	}

	//获取第一车网车辆信息方法
	private FirstCarInfo getFirstCarInfo(Car car, FirstCarResult firstCarResultLogin, FirstCarInfo firstCarInfo){

		//获取颜色
		Integer color = firstCarApi.getColorId(car.getCarOutColor());

		//获取年份
		Integer purchase_year = null;
		try {
			purchase_year = getYearByVin(car.getCarVin());
		} catch (Exception e) {
			logger.error("根据vin获取年份失败！", e);
			return null;
		}

		//获取城市关系
		Market market = new Market();
		market.setMarketId(car.getMarketId());
		List<Market> marketList = marketService.selectMarketList(market);
		if (marketList == null || marketList.size() == 0){
			logger.info("获取城市时获取市场信息失败！");
			return null;
		}
		CityMappingThirdparty cityMappingThirdparty = new CityMappingThirdparty();
		cityMappingThirdparty.setCityId(marketList.get(0).getCityId());
		cityMappingThirdparty.setCityType(1);
		List<CityMappingThirdparty> cityMappingThirdpartyList = null;
		try {
			cityMappingThirdpartyList = cityMappingThirdpartyDao.selectCityMappingThirdpartyList(cityMappingThirdparty);
			if (cityMappingThirdpartyList == null || cityMappingThirdpartyList.size() == 0){
				logger.info("获取城市失败！");
				return null;
			}
			if (cityMappingThirdpartyList.get(0).getCityThirdpartyId() == 0){
				logger.info("第一车网无此城市！");
				return null;
			}
		} catch (Exception e) {
			logger.error("获取城市失败！", e);
			return null;
		}
		Integer province_id = cityMappingThirdpartyList.get(0).getProvinceThirdpartyId();
		Integer city_id = cityMappingThirdpartyList.get(0).getCityThirdpartyId();

		//获取市场地址
		String car_location = marketList.get(0).getMarketAddress();

		// 获取车型库关系
		ModelMappingThirdparty modelMappingThirdparty = new ModelMappingThirdparty();
		modelMappingThirdparty.setModelId(car.getModelId());
		modelMappingThirdparty.setModelType(1);
		Integer model_simple_id = null;
		try {
			List<ModelMappingThirdparty> modelMappingThirdpartyList = modelMappingThirdpartyDao.selectModelMappingThirdpartyList(modelMappingThirdparty);
			if (modelMappingThirdpartyList == null || modelMappingThirdpartyList.size() == 0){
				logger.info("获取车型库关系失败！");
				return null;
			}
			if (modelMappingThirdpartyList.get(0).getModelThirdpartyId() == 0){
				logger.info("第一车网车型库无此车型，发布失败！");
				return null;
			}
			model_simple_id = modelMappingThirdpartyList.get(0).getModelThirdpartyId();
		} catch (Exception e) {
			logger.error("获取车型库关系失败！", e);
			return null;
		}

		//获取图片信息
		CarImage carImage = new CarImage();
		carImage.setCarId(car.getCarId());
		List<String> usedcar_photo_urls = null;
		List<String> usedcar_photo_url = null;
		try {
			List<CarImage> carImages = carImageDao.selectCarImageList(carImage, 3);
			usedcar_photo_urls = new ArrayList<>();
			usedcar_photo_url = new ArrayList<>();
			if(carImages != null && carImages.size() > 0){
				String imageUrl = null;
				for (CarImage carImg : carImages) {
					imageUrl = Constant.FDFS_CONTENT_PATH + carImg.getImageUrl();
					if(carImg.getImageKey().equals("control_booth")){
						usedcar_photo_urls.add(imageUrl);
					}
					if(carImg.getImageKey().equals("driving_seat")){
						usedcar_photo_urls.add(imageUrl);
					}
					if(carImg.getImageKey().equals("engine_bay")){
						usedcar_photo_urls.add(imageUrl);
					}
					if(carImg.getImageKey().equals("gear_lever")){
						usedcar_photo_urls.add(imageUrl);
					}
					if(carImg.getImageKey().equals("left_anterior")){
						usedcar_photo_urls.add(imageUrl);
					}
					if(carImg.getImageKey().equals("odograph")){
						usedcar_photo_urls.add(imageUrl);
					}
					if(carImg.getImageKey().equals("open_trunk")){
						usedcar_photo_urls.add(imageUrl);
					}
					if(carImg.getImageKey().equals("right_rear")){
						usedcar_photo_urls.add(imageUrl);
					}
					if(carImg.getImageKey().equals("right_side")){
						usedcar_photo_urls.add(imageUrl);
					}
					if(carImg.getImageKey().equals("tyre")){
						usedcar_photo_urls.add(imageUrl);
					}
				}
			}
			//上传第一车网服务器封装返回图片地址
			int j = 1;
			for (String s : usedcar_photo_urls){
				int i = 1;
				FirstCarResult firstCarResultUrl = null;
				while (i<=3) {
					firstCarResultUrl = firstCarApi.uploadImage(firstCarInfo.getUploadXml(firstCarResultLogin.getSid(), firstCarResultLogin.getShop_id(), s));
					logger.info("LIST第 " + j + "张图" + "第" + i + " 次上传，url：" + s);
					if(StringUtils.isNotEmpty(firstCarResultUrl.getUrl())){
						break;
					}
					i++;
				}
				if(StringUtils.isNotEmpty(firstCarResultUrl.getError())){
					logger.info("图片上传第一车网失败，提示码：" + firstCarResultUrl.getError_code() + "  ，提示信息：" + new String(firstCarResultUrl.getError().getBytes(),"UTF-8"));
					return null;
				}
				usedcar_photo_url.add(firstCarResultUrl.getUrl());
				j++;
			}
		} catch (Exception e) {
			logger.error("启辕获取图片失败或上传第一车网失败", e);
			return null;
		}

		//获取首图地址
		FirstCarResult firstCarResultCarPhotoUrl = null;
		int i = 1;
		try {
			while (i<=3) {
				firstCarResultCarPhotoUrl = firstCarApi.uploadImage(firstCarInfo.getUploadXml(firstCarResultLogin.getSid(), firstCarResultLogin.getShop_id(), Constant.FDFS_CONTENT_PATH + car.getCarImageUrl()));
				logger.info("首图第 " + i + " 次上传");
				if(StringUtils.isNotEmpty(firstCarResultCarPhotoUrl.getUrl())){
					break;
				}
				i++;
			}
			if(StringUtils.isNotEmpty(firstCarResultCarPhotoUrl.getError())){
				logger.info("第一车网设为上架失败，提示码：" + firstCarResultCarPhotoUrl.getError_code() + "  ，提示信息：" + new String(firstCarResultCarPhotoUrl.getError().getBytes(),"UTF-8"));
				return null;
			}
		} catch (Exception e) {
			logger.error("首图上传第一车网失败", e);
			return null;
		}
		String car_photo_url = firstCarResultCarPhotoUrl.getUrl();

		firstCarInfo = new FirstCarInfo(car, model_simple_id, usedcar_photo_url, color, purchase_year, car_photo_url, province_id, city_id, car_location);
		return firstCarInfo;
	}

	//获取车辆信息方法
	private Car getCarInfo(Car car){
		try {
			Car selectCar = new Car();
			selectCar.setCarId(car.getCarId());
			car = carDao.selectCar(selectCar);
			if(car == null){
				logger.info("第一车网接口获取车辆信息失败！");
				return null;
			}
		} catch (Exception e) {
			logger.error("第一车网接口获取车辆信息失败！", e);
			return null;
		}
		return car;
	}

	//根据Vin获取年份方法
	private Integer getYearByVin(String vin) throws Exception {
		Integer VinYear = null;
		char yearCode = ' ';
		if (vin.length() == 17) {
			yearCode = vin.toUpperCase().toCharArray()[9];
		} else {
			return null;
		}
		switch (yearCode) {
			case '1': VinYear = 2001 ; break;
			case '2': VinYear = 2002 ; break;
			case '3': VinYear = 2003 ; break;
			case '4': VinYear = 2004 ; break;
			case '5': VinYear = 2005 ; break;
			case '6': VinYear = 2006 ; break;
			case '7': VinYear = 2007 ; break;
			case '8': VinYear = 2008 ; break;
			case '9': VinYear = 2009 ; break;
			case 'A': VinYear = 2010 ; break;
			case 'B': VinYear = 2011 ; break;
			case 'C': VinYear = 2012 ; break;
			case 'D': VinYear = 2013 ; break;
			case 'E': VinYear = 2014 ; break;
			case 'F': VinYear = 2015 ; break;
			case 'G': VinYear = 2016 ; break;
			case 'H': VinYear = 2017 ; break;
			case 'J': VinYear = 2018 ; break;
			case 'K': VinYear = 2019 ; break;
			case 'L': VinYear = 2020 ; break;
			case 'M': VinYear = 2021 ; break;
			case 'N': VinYear = 2022 ; break;
			case 'P': VinYear = 2023 ; break;
			case 'R': VinYear = 2024 ; break;
			case 'S': VinYear = 2025 ; break;
			case 'T': VinYear = 2026 ; break;
			case 'V': VinYear = 2027 ; break;
			case 'W': VinYear = 2028 ; break;
			case 'X': VinYear = 2029 ; break;
			case 'Y': VinYear = 2000 ; break;
			default: VinYear = 0; break;
		}
		return VinYear;
	}

}
